import axios from 'axios';
import { API_URL } from './config';

const setWxConfig = ($wx, config, debug) => {
  $wx.config({
    debug: debug,
    appId: config.appId,
    timestamp: config.timestamp,
    nonceStr: config.noncestr,
    signature: config.signature,
    jsApiList: [
      'onMenuShareAppMessage',
      'onMenuShareTimeline',
      'onMenuShareQQ',
      'onMenuShareWeibo',
      'onMenuShareQZone',
      'chooseWXPay',
      'previewImage',
      'getLocation',
      'openLocation',
      'updateTimelineShareData',
      'updateAppMessageShareData',
      'hideMenuItems',
      'showMenuItems',
      'scanQRCode',
    ],
  });
  $wx.ready(() => {
    // console.log('wechat ready....');
    $wx.hideMenuItems({
      menuList: ['menuItem:copyUrl'],
    });
  });
  $wx.error(error => {
    // console.error('wechat config error....', error);
  });
};

const wxConfig = ($wx, debug) => {
  const url = `${API_URL}/api/weixin?url=${encodeURIComponent(
    location.href.split('#')[0]
  )}`;
  axios
    .get(url, {
      headers: {
        'Content-Type': 'application/json',
      },
    })
    .then(res => {
      res = res.data;
      if (res && res.code == 200) {
        setWxConfig($wx, res.data, debug);
      } else {
        return Promise.reject(res.error);
      }
    })
    .catch(error => {
      // console.log(error);
    });
};

const wxShare = ($wx, data, url) => {
  let link =
    'https://m.hangzhouhaiyu.com/douwu/#/index?activityid=' + data.activity_id;
  if (url) {
    link = url;
  }

  const shareTitle = data.share_title;
  const shareImg = data.share_bg_img;
  const shareText = data.share_content
    ? data.share_content
    : '有机会赢取超高价值的豪礼哦';

  $wx &&
    $wx.ready(() => {
      $wx.updateTimelineShareData({
        title: shareTitle, // 分享标题
        link, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
        imgUrl: shareImg,
      });

      $wx.onMenuShareTimeline({
        title: shareTitle,
        link,
        imgUrl: shareImg,
      });

      $wx.updateAppMessageShareData({
        title: shareTitle,
        desc: shareText,
        link,
        imgUrl: shareImg,
      });

      $wx.onMenuShareAppMessage({
        title: shareTitle,
        desc: shareText,
        link,
        imgUrl: shareImg,
      });
    });
};

export default {
  setWxConfig,
  wxConfig,
  wxShare,
};
